const jwt = require("jsonwebtoken");
const { userNotLogin, tokenExpiredError, invalidToken, hasNotAdminPermission } = require("../constant/error.type");
/**token验证 */
const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header
  if (!authorization) {
    console.error(userNotLogin.message)
    return ctx.app.emit('error', userNotLogin, ctx)
  }
  const token = authorization.replace('Bearer ', '')
  try {
    const user = jwt.verify(token, process.env.JWT_SECRET)
    // 存储user信息
    ctx.state.user = user
  } catch (error) {
    switch (error.name) {
      case 'TokenExpiredError':
        console.error(tokenExpiredError.message, error)
        return ctx.app.emit('error', tokenExpiredError, ctx)
      case 'JsonWebTokenError':
        console.error(invalidToken.message, error)
        return ctx.app.emit('error', invalidToken, ctx)
    }
  }
  await next()
}
/**验证管理员权限 */
const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user
  if (!is_admin) {
    console.error(hasNotAdminPermission.message)
    ctx.app.emit('error', hasNotAdminPermission, ctx)
    return
  }
  await next()
}
module.exports = {
  auth,
  hadAdminPermission
}